import glUtils from "../utils/glUtils";
import filtUtils from "../utils/filtUtils";

export default {

    gl: null,
    vao: 0,
    vbo: 0,
    bInited: false,

    // handle
    vN: 0,

    init(gl) {
        this.gl = gl;

        let self = this;
        filtUtils.async_loadFiles([
            'shaders/test_uniformblock_vs.glsl',
            'shaders/test_uniformblock_fs.glsl',
        ]).then((lstShader) => {
            // console.log('vs:',lstShader[0]);
            // console.log('fs:',lstShader[1]);
            self.onInit(lstShader[0], lstShader[1]);
        }).catch(() => {
            console.error('load shader error!');
        });
    },

    onInit(vs, fs) {
        this.bInited = true;

        let gl = this.gl;
        this.program = glUtils.createProgram(gl, vs, fs);
        gl.useProgram(this.program);

        this.vN = gl.getAttribLocation(this.program, 'n');

        this.vao = gl.createVertexArray();
        gl.bindVertexArray(this.vao);

        this.vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, this.vbo);
        gl.bufferData(gl.ARRAY_BUFFER, new Uint32Array([0, 1, 2]), gl.STATIC_DRAW);
        gl.vertexAttribIPointer(this.vN, 1, gl.UNSIGNED_INT, 0, 0);
        gl.enableVertexAttribArray(this.vN);

        // 使用 uniform块
        this.uboIdx = gl.getUniformBlockIndex(this.program, "Vertice");


        let Data = new Float32Array([
            -0.9, -0.9, 0.0, 1.0,
            0.9, -0.9, 0.0, 1.0,
            0.0, 0.9, 0.0, 1.0,

            // color
            0.0, 0.5, 0.0, 1.0
        ]);

        // 对 验证数据是否正确
        let blockSize = gl.getActiveUniformBlockParameter(this.program, this.uboIdx, gl.UNIFORM_BLOCK_DATA_SIZE);
        let lstIndices = gl.getUniformIndices(this.program, ['v', 'color']);
        let lstOffset = gl.getActiveUniforms(this.program, lstIndices, gl.UNIFORM_OFFSET);

        const ItemSize = Float32Array.BYTES_PER_ELEMENT;
        if(blockSize !== Data.length * ItemSize){
            console.error(`blockSize:${blockSize} 和 Data.Size:${Data.length * ItemSize} 不相等`);
            return;
        }

        if(lstOffset[0] !== 0 || lstOffset[1] !== 12 * ItemSize){
            console.error(`offset[0]:${lstOffset[0]} 和 offset[1]:${lstOffset[1]} 不相等`);
            return;
        }

        this.ubo = gl.createBuffer();
        gl.bindBuffer(gl.UNIFORM_BUFFER,this.ubo);
        gl.bufferData(gl.UNIFORM_BUFFER,Data,gl.STATIC_DRAW);
        gl.bindBufferBase(gl.UNIFORM_BUFFER,this.uboIdx,this.ubo);

        gl.bindVertexArray(null);
    },

    render(){
        if(!this.bInited){
            return;
        }

        let gl = this.gl;

        gl.useProgram(this.program);
        gl.bindVertexArray(this.vao);
        gl.drawArrays(gl.TRIANGLES,0,3);
        gl.bindVertexArray(null);
    },
}